package com.qf.cs2203Spring07.aop;

import com.qf.cs2203Spring07.aop.anno.Retry;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;

@Aspect
@Component
public class MyAspect {

//    @Around("@annotation(com.qf.cs2203Spring07.aop.anno.Retry)")
    public Object RetryToGetMoney(ProceedingJoinPoint joinPoint) throws Throwable {
//        System.out.println("963852");
//        String name = joinPoint.getTarget().getClass().getName();
//        System.out.println("method="+methodName);
//        System.out.println("name="+name);
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        String methodName = joinPoint.getSignature().getName();
        Method method = methodSignature.getMethod();
        Method declaredMethod = joinPoint.getTarget().getClass().getDeclaredMethod(methodName, method.getParameterTypes());
        Retry annotation1 = declaredMethod.getAnnotation(Retry.class);
        //Retry annotation = method.getAnnotation(Retry.class);
        System.out.println("annotation1_RetryNum="+annotation1.RetryNum());
        System.out.println("annotation1_CLASS="+annotation1.CLASS());
//        Retry annotation = methodSignature.getMethod().getAnnotation(Retry.class);
//        System.out.println("annotation="+annotation.CLASS());
//        Class clazz = Class.forName(name);
        Object proceed = 110;
        for (int i = 0; i < annotation1.RetryNum(); i++){
            try {
                proceed = joinPoint.proceed();
                System.out.println("proceed="+proceed);
                if((Integer) proceed == 1){
                    break;
                }
            } catch (Throwable e) {
                if(e.getClass().equals(annotation1.CLASS())){
                    System.out.println("====================================================================");
                    System.out.println(Thread.currentThread().getName()+"第"+i+"次购买失误");
                    System.out.println("====================================================================");
                }else {
                    e.printStackTrace();
                    break;
                }
            }
        }
        return proceed;
    }

    public void afterThrowing(){

    }
}
